package com.datagrid;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.util.NumUtil;

public class DatagridAction extends ActionSupport {
	private static final long serialVersionUID = -3165303147616987955L;

	private List<Map<String, String>> list;
	private Map<String, Object> map = new HashMap<String, Object>();
	private Map<String, Object> result = new HashMap<String, Object>();

	public List<Map<String, String>> getList() {
		return list;
	}

	public void setList(List<Map<String, String>> list) {
		this.list = list;
	}

	public Map<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}
	
	public Map<String, Object> getResult() {
		return result;
	}

	public void setResult(Map<String, Object> result) {
		this.result = result;
	}

	public DatagridAction() {
		
	}

	public String getUsers() {
		String pageStr = ServletActionContext.getRequest().getParameter("page");
		String rowsStr = ServletActionContext.getRequest().getParameter("rows");
		
		int page = NumUtil.parseInt(pageStr, 1);
		int rows = NumUtil.parseInt(rowsStr, 10);
		System.out.println(page + "----" + rows);
		
		list = DatagridDataRepo.get(page, rows);
		map.put("total", DatagridDataRepo.size());
		map.put("rows", list);
		
		return SUCCESS;
	}
	
	private Map<String, String> getFormItem() {
		Map<String, String> item = new HashMap<String, String>();
		
		Enumeration<String> params = ServletActionContext.getRequest().getParameterNames();
		while (params.hasMoreElements()) {
			String key = params.nextElement();
			String value = ServletActionContext.getRequest().getParameter(key);
			System.out.println(key + " - " + value);
			item.put(key, value);
		}
		
		return item;
	}

	public String saveUser() {
		Map<String, String> item = getFormItem();
		
		if (item.get("firstname").equals("admin")) {
			result.put("errorMsg", "first name must be not admin");
		} else {
			DatagridDataRepo.addItem(item);
			result.put("success", true);
		}

		return SUCCESS;
	}
	
	public String updateUser() {
		Map<String, String> item = getFormItem();
		if (item.get("firstname").equals("admin")) {
			result.put("errorMsg", "update: first name must be not admin");
		} else {
			DatagridDataRepo.updateItem(item);
			result.put("success", true);
		}
		return SUCCESS;
	}
	
	public String destroyUser() {
		String id = ServletActionContext.getRequest().getParameter("id");
		if (id != null && id.equals("id-39")) {
			result.put("errorMsg", "cannot remove this item[id-39]");
		} else {
			System.out.println("remove item:" + id);
			DatagridDataRepo.removeItem(id);
			result.put("success", true);
		}
		return SUCCESS;
	}
}
